package cn.xlbweb.cli.config;

import cn.xlbweb.cli.common.CommonProperties;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

/**
 * @author: bobi
 * @date: 2018/11/7 22:31
 * @description:
 */
@Configuration
@EnableSwagger2
@Slf4j
public class ApiConfig {

    @Autowired
    private CommonProperties commonProperties;

    @Bean
    public Docket createRestApi() {
        log.info("Init swagger3 api...");
        return new Docket(DocumentationType.OAS_30)
                .groupName("simple-cli")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.xlbweb.cli"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("wudibo", "http://www.xlbweb.cn", "super-wudibo@foxmail.com");
        return new ApiInfoBuilder()
                .title("分离开发简易脚手架API文档")
                .description("关于作者")
                .termsOfServiceUrl("https://git.xlbweb.cn")
                .contact(contact)
                .version("v1.0.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        ApiKey apiKey = new ApiKey(commonProperties.getTokenName(), commonProperties.getTokenName(), In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    private List<SecurityContext> securityContexts() {
        SecurityReference securityReference = new SecurityReference(commonProperties.getTokenName(), new AuthorizationScope[]{new AuthorizationScope("global", "请输入token信息")});
        SecurityContext securityContext = SecurityContext.builder().securityReferences(Collections.singletonList(securityReference)).build();
        return Collections.singletonList(securityContext);
    }
}
